#ifndef __HttpUpdate_h
#define __HttpUpdate_h
#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266httpUpdate.h>

// 升级标志
bool update_flag = false;
char update_url[100];
int update_err_cnt = 0;

// update
void update_started()
{
  Serial.println("CALLBACK:  HTTP update process started");
}

void update_finished()
{
  Serial.println("CALLBACK:  HTTP update process finished");
}

void update_progress(int cur, int total)
{
  Serial.printf("CALLBACK:  HTTP update process at %d of %d bytes...\n", cur, total);
}

void update_error(int err)
{
  Serial.printf("CALLBACK:  HTTP update fatal error code %d\n", err);
  update_err_cnt += 1;
  if (update_err_cnt >= 10){
    resetFunc();    //重启程序开始
  }
}

void update_setup()
{
  ESPhttpUpdate.setLedPin(BUILTIN_LED, LOW);

  // Add optional callback notifiers
  ESPhttpUpdate.onStart(update_started);
  ESPhttpUpdate.onEnd(update_finished);
  ESPhttpUpdate.onProgress(update_progress);
  ESPhttpUpdate.onError(update_error);
}

void update_run(WiFiClient& client, char *url)
{
  Serial.println("update url:");
  Serial.println(url);
  // t_httpUpdate_return ret = ESPhttpUpdate.update(espClient, "http://rgt-fushe.oss-cn-beijing.aliyuncs.com/FSC/httpUpdate.bin");
  t_httpUpdate_return ret = ESPhttpUpdate.update(client, url);
  // Or:
  //t_httpUpdate_return ret = ESPhttpUpdate.update(client, "server", 80, "file.bin");

  switch (ret)
  {
  case HTTP_UPDATE_FAILED:
    Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
    break;

  case HTTP_UPDATE_NO_UPDATES:
    Serial.println("HTTP_UPDATE_NO_UPDATES");
    break;

  case HTTP_UPDATE_OK:
    Serial.println("HTTP_UPDATE_OK");
    break;
  }
}



#endif
